//
//  GetNearBySpotTask.m
//  ZooNgonDoiOS
//
//  Created by Anh Jun Linh Tinh on 7/4/12.
//  Copyright (c) 2012 Personal. All rights reserved.
//

#import "GetNearBySpotTask.h"
#import "RestKit/JSONKit.h"
#import "ZooSpotBean.h"

@implementation GetNearBySpotTask

-(id)initWithParams:(NSString *)lon lat:(NSString *)lat{
    self = [self initWithParams:lon lat:lat limit:0 acclevel:2];
    return self;
}
-(id) initWithParams:(NSString *)lon lat:(NSString *)lat limit:(int)limit{
    self = [self initWithParams:lon lat:lat limit:limit acclevel:2];
    return self;
}

-(id)initWithParams:(NSString *)lon lat:(NSString *)lat limit:(int)limit acclevel:(int)accLvl{
    self = [super init];
    if(self){
        _long = lon;
        _lat = lat;
        _limit = limit;
        _accLvl = accLvl;
    }
    return self;
}
-(void) doExecute:(id)pCaller callback:(SEL)pCallback{
    NSMutableArray *arrKeys = [[NSMutableArray alloc] init];
    NSMutableArray *arrValues = [[NSMutableArray alloc] init];
    [arrKeys addObject:@"long"];
    [arrKeys addObject:@"lat"];
    [arrValues addObject:_long];
    [arrValues addObject:_lat];
    
    _target = pCaller;
    _selector = pCallback;
    
    if (_limit > 0) {
        [arrKeys addObject:@"limit"];
        NSString* strLimit = [NSString stringWithFormat:@"%i", _limit];
        [arrValues addObject:strLimit];
    }
   
    if (_accLvl > 0) {
         [arrKeys addObject:@"max_distance"];
         NSString* strAccLvl = [NSString stringWithFormat:@"%i", _accLvl];
        [arrValues addObject:strAccLvl];
    }
    NSDictionary *params = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];
    [[RKObjectManager sharedManager].client get:@"/spot/nearby" queryParameters:params delegate:self];
}

-(void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error{
       NSLog(@"a"); 
}

-(void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response{
    NSString *jsonString = [response bodyAsString];
    NSDictionary *json = [jsonString objectFromJSONString];
    NSArray *arrDatas = [json objectForKey:@"data"];
    NSMutableArray *result = [[NSMutableArray alloc] init];
    int size = [arrDatas count];
    if(size > 0){    
        for(int i=0;i<size;i++){
            NSDictionary *spotDic = [arrDatas objectAtIndex:i];
            ZooSpotBean *spotItem = [[ZooSpotBean alloc] init];
            spotItem.id_spot = [spotDic objectForKey:@"id"];
            spotItem.name = [spotDic objectForKey:@"name"];
            spotItem.lon = [spotDic objectForKey:@"lon"];
            spotItem.lat = [spotDic objectForKey:@"lat"];
            [result addObject:spotItem];
        }
    }
    //call back result
    [_target performSelector:_selector withObject:result];
    
}

@end
